package com.springboot.chatroom.controller;


import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

/**
 * Created with IntelliJ IDEA.
 * Description :
 * User: jiume
 * Date: 2025-04-17
 * Time: 20:26
 */
@Slf4j
@Component
public class TextWebSocketController extends TextWebSocketHandler {
    /**
     * webSocket 连接建立成功之后自动调用
     * @param session webSocket连接所对应的会话
     * @throws Exception
     */
    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        log.info("webSocket 连接建立成功...");
        super.afterConnectionEstablished(session);
    }

    /**
     * websocket 收到消息之后，自动调用
     * @param session webSocket连接所对应的会话
     * @param message 收到的消息所对应的值
     * @throws Exception
     */
    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        log.info("webSocket 连接收到消息..." + message.toString());
        // webSocket 是会话，里面记录了通信双方的信息
        session.sendMessage(message);
        super.handleTextMessage(session, message);
    }

    /**
     * webSocket 连接出现异常时，自动调用（例如，断网了）
     * @param session webSocket连接所对应的会话
     * @param exception 记录的是异常信息
     * @throws Exception
     */
    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        log.info("webSocket 连接出现异常(连接异常关闭)...");
        super.handleTransportError(session, exception);
    }

    /**
     * webSocket 连接正常关闭之后，自动调用该方法
     * 上面的相当于是连接异常关闭之后，自动调用的方法
     * @param session webSocket连接所对应的会话
     * @param status 关闭的状态
     * @throws Exception
     */
    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        log.info("webSocket 连接正常关闭...");
        super.afterConnectionClosed(session, status);
    }
}
